package com.ahearttogo.statement;

import com.ahearttogo.binding.MapperMethod;
import com.ahearttogo.result.DefaultResultSetHandler;
import com.ahearttogo.result.ResultSetHandler;
import com.ahearttogo.session.Configuration;
import com.ahearttogo.util.DbUtil;
import lombok.Data;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @author xiejialin
 * @date 2020/4/22 10:07 AM
 */
@Data
public class StatementHandler {

    private Configuration configuration;

    private ResultSetHandler resultSetHandler;

    public StatementHandler() {
    }

    public StatementHandler(Configuration configuration, ResultSetHandler resultSetHandler) {
        this.configuration = configuration;
        this.resultSetHandler = resultSetHandler;
    }

    public StatementHandler(Configuration configuration) {
        this.configuration = configuration;
        resultSetHandler=new DefaultResultSetHandler();
    }

    public <T> T query(MapperMethod method, Object parameter) throws Exception {
        Connection connection= DbUtil.open();
        PreparedStatement preparedStatement = connection.prepareStatement(String.format(method.getSql(),Integer.parseInt(String.valueOf(parameter))));
        preparedStatement.execute();
        return resultSetHandler.handle(preparedStatement,method);
    }
 }
